package com.jueban.serviceImpl;

import com.jueban.Dto.AnnouncementQueryDto;
import com.jueban.Vo.AnnouncementVo;
import com.jueban.Vo.AnnouncementsVo;
import com.jueban.model.Announcement;
import com.jueban.repository.AnnouncementRepository;
import com.jueban.service.AnnouncementService;
import com.jueban.util.Messages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AnnouncementServiceImpl implements AnnouncementService
{

    @Autowired
    private AnnouncementRepository announcementRepository;

    //添加公告
    @Override
    public AnnouncementVo addAnnouncement(Announcement announcement)
    {
        AnnouncementVo announcementVo = new AnnouncementVo(announcement);
        announcement.setCreateTime(new Date());
        announcementRepository.save(announcement);
        announcementVo.setMessages(Messages.ADD_SUCCEED);
        return announcementVo;
    }

    //根据ID删除公告
    @Override
    public AnnouncementVo deleteAnnouncementById(Integer id)
    {
        announcementRepository.delete(id);
        AnnouncementVo announcementVo = new AnnouncementVo();
        announcementVo.setMessages(Messages.DEL_SUCCEED);
        return announcementVo;
    }

    //更新公告内容
    @Override
    public AnnouncementVo updateAnnouncement(Announcement announcement)
    {
        announcement.setCreateTime(new Date());
        announcementRepository.save(announcement);
        AnnouncementVo announcementVo = new AnnouncementVo();
        announcementVo.setMessages("修改成功！");
        return announcementVo;

    }

    //根据ID获取公告
    @Override
    public AnnouncementVo getAnnouncementById(Integer id)
    {
        Announcement announcement = announcementRepository.findOne(id);
        AnnouncementVo announcementVo = new AnnouncementVo(announcement);
        if(announcement == null)
        {
            announcementVo.setMessages(Messages.GET_FAIL);
            return announcementVo;
        }
        announcementVo.setMessages(Messages.GET_SUCCEED);
        return announcementVo;
    }

    @Override
    public AnnouncementsVo getAnnouncements(AnnouncementQueryDto announcementDto)
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = new PageRequest(announcementDto.getOffset(), announcementDto.getPageSize(), sort);
        Page<Announcement> page = announcementRepository.findAll(pageable);
        AnnouncementsVo announcementsVo = new AnnouncementsVo();
        announcementsVo.setProperties(page);
        return announcementsVo;
    }
}
